import curses
import psutil

def main(stdscr):
    # 清除屏幕
    stdscr.clear()

    # 获取终端的尺寸
    height, width = stdscr.getmaxyx()

    # 创建四个窗口
    
    cpu_window = curses.newwin(int(height/2), int(width/2), 0, 0)
    io_window = curses.newwin(int(height/2), int(width/2), 0, int(width/2))
    network_window = curses.newwin(int(height/2), int(width/2), int(height/2), 0)
    memory_window = curses.newwin(int(height/2), int(width/2), int(height/2), int(width/2))

    # 设置窗口边框
    cpu_window.box()
    io_window.box()
    network_window.box()
    memory_window.box()

    # 开启实时刷新
    stdscr.nodelay(True)

    while True:
        # 获取键盘输入
        key = stdscr.getch()

        # 如果按下 "q" 键，退出程序
        if key == ord('q'):
            break

        # 获取 CPU 使用率
        cpu_percent = psutil.cpu_percent()
        cpu_text = f"CPU Usage: {cpu_percent}%"
        cpu_window.addstr(1, int((width/2 - len(cpu_text)) / 2), cpu_text)

        # 获取 IO 使用率
        io_counters = psutil.disk_io_counters()
        io_text = f"IO Usage: {io_counters.read_bytes/1024/1024}MB/s"
        io_window.addstr(1, int((width/2 - len(io_text)) / 2), io_text)

        # 获取网络使用率
        netio_counters = psutil.net_io_counters()
        network_text = f"Network Usage: {netio_counters.bytes_recv/1024/1024}MB/s"
        network_window.addstr(1, int((width/2 - len(network_text)) / 2), network_text)

        # 获取内存使用率
        memory_percent = psutil.virtual_memory().percent
        memory_text = f"Memory Usage: {memory_percent}%"
        memory_window.addstr(1, int((width/2 - len(memory_text)) / 2), memory_text)

        # 刷新窗口
        cpu_window.refresh()
        io_window.refresh()
        network_window.refresh()
        memory_window.refresh()

        # 每秒刷新一次
        curses.napms(1000)


# 运行主函数
curses.wrapper(main)